package com.hyjr.collect.netty.handler;

import java.util.List;

import com.hyjr.bean.TaskBean;
import com.hyjr.common.data.ResultData;
import com.hyjr.common.utils.LogUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class SendTaskClientHandler extends ChannelInboundHandlerAdapter {
	private List<TaskBean> taskBeanList;

	public SendTaskClientHandler(List<TaskBean> taskBeanList) {
		this.taskBeanList = taskBeanList;
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelInactive(ctx);
		LogUtils.debug("采集端，客户端SendTaskClientHandler，channelInactive！");
	}

	public void channelActive(ChannelHandlerContext ctx) {
		TaskBean taskBean = taskBeanList.get(0);
		taskBeanList.remove(0);
		ctx.writeAndFlush(taskBean);
		LogUtils.debug("采集端，客户端SendTaskClientHandler，channelActive，发送任务数据，还剩任务数据数：" + taskBeanList.size() + "，任务数据：" + taskBean.toString());
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof ResultData) {
			ResultData resultData = (ResultData) msg;
			LogUtils.debug("采集端，客户端SendTaskClientHandler，channelRead，发送任务数据后返回结果：" + resultData.getCode() + "===" + resultData.getErrorMsg());
			
			if(taskBeanList.size() == 0) {
				channelInactive(ctx);
			} else {
				TaskBean taskBean = taskBeanList.get(0);
				taskBeanList.remove(0);
				ctx.writeAndFlush(taskBean);
				LogUtils.debug("采集端，客户端SendTaskClientHandler，channelActive，发送任务数据，还剩任务数据数：" + taskBeanList.size() + "，任务数据：" + taskBean.toString());
			}
			
		}
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
		LogUtils.debug("采集端，客户端SendTaskClientHandler，exceptionCaught", cause);
	}

}
